/*
 * kylin-os-manager
 *
 * Copyright (C) 2022, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "mainwindow.h"
#include "common.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QDebug>
#include <QString>
#include <QApplication>
#include <QScreen>
#include <fcntl.h>

#include <usermanual.h>

static const QString PLUGIN_BODY_CHECK = "Plugin-BodyCheck";
static const QString PLUGIN_ISSUS_REPAIR = "Plugin-IssusRepair";
static const QString PLUGIN_RUBBISH_CLEAR = "Plugin-RubbishClear";
static const QString PLUGIN_MULTI_TERMINAL = "Plugin-MultiTerminal";
static const QString PLUGIN_TOOL_BOX = "Plugin-ToolBox";

static constexpr char TR_BODY_CHECK[] = "BodyCheck";
static constexpr char TR_ISSUS_REPAIR[] = "IssueRepair";
static constexpr char TR_RUBBISH_CLEAR[] = "RubbishClear";
static constexpr char TR_MULTI_TERMINAL[] = "MultiTerminal";
static constexpr char TR_TOOL_BOX[] = "ToolBox";

MainWindow::MainWindow(QVector<KyManagerPluginProvider *> plugins, QWidget *parent)
    : KWidget(parent), m_plugins(plugins)
{
    // resize(MainWindowWidth,MainWindowHeight);
    setFixedSize(MainWindowWidth, MainWindowHeight);

    QRect availableGeometry = qApp->primaryScreen()->availableGeometry();
    this->move((availableGeometry.width() - this->width()) / 2, (availableGeometry.height() - this->height()) / 2);

    this->setIcon("kylin-os-manager");
    this->setWidgetName(tr("kylin-os-manager"));
    connect(windowButtonBar()->closeButton(), &QPushButton::clicked, this, [this]() {
        qDebug() << "MainWindow::MainWindow:closeButton is clicked!";
        if (mSingleInstanceFd) {
            lockf(mSingleInstanceFd, F_ULOCK, 0);
        }
    });

    //    this->setAttribute(Qt::WA_DeleteOnClose);
    setWindowTitle(tr("kylin-os-manager"));
    this->setLayoutType(HorizontalType);

    if (initPluginsInfo()) {
        initNavigationArea();
        initMainWorkArea();
        initConnectSig();
        setFirstWidget();
    }
}

MainWindow::~MainWindow() {}
void MainWindow::slotCloseBtnIsClicked() {}
void MainWindow::initNavigationArea()
{
    QVBoxLayout *mNaviVLayout = new QVBoxLayout();
    mNaviVLayout->setSpacing(0);
    mNaviVLayout->setContentsMargins(10, 0, 10, 0);
    mNaviVLayout->addSpacing(SpaceLoginTop);
    mNaviVLayout->addWidget(mNaviBar);
    sideBar()->setLayout(mNaviVLayout);

    windowButtonBar()->maximumButton()->setVisible(false);
    windowButtonBar()->menuButton()->setVisible(false);
}
//用来准备要加载的插件信息
bool MainWindow::initPluginsInfo()
{
    //通过接口获取都有哪些插件
    Utils util;
    QMap<QString, pluginconfig_t> mAllLoadMap = util.getPluginConfig();
    if (mAllLoadMap.isEmpty()) {
        qWarning() << "MainWindow::initPluginsInfo mAllLoadMap.isEmpty!";
        return false;
    }
    mNeedLoadVector.clear();
    mNeedLoadVector = util.getLoadPlugin(mAllLoadMap);
    if (mNeedLoadVector.isEmpty()) {
        qWarning() << "MainWindow::initPluginsInfo mNeedLoadVector.isEmpty!";
        return false;
    }
    //这里可以添加逻辑，进行进一步的筛选
    //对界面进行初始化
    QVector<QString>::iterator iter;
    mNaviBar = new KNavigationBar(this);
    for (iter = mNeedLoadVector.begin(); iter != mNeedLoadVector.end(); iter++) {
        QIcon icon;
        icon.actualSize(QSize(16, 16));
        if (*iter == PLUGIN_ISSUS_REPAIR) {
            if (QIcon::hasThemeIcon("ukui-troubleshooting-symbolic")) {
                icon = QIcon::fromTheme("ukui-troubleshooting-symbolic");
            } else {
                icon = QIcon(":/res/ukui-troubleshooting-symbolic.svg");
            }
            QStandardItem *mIssueRepair = new QStandardItem(icon, tr("Fault Detection"));
            mNaviBar->addItem(mIssueRepair);
        } else if (*iter == PLUGIN_RUBBISH_CLEAR) {
            if (QIcon::hasThemeIcon("ukui-rubbish-symbolic")) {
                icon = QIcon::fromTheme("ukui-rubbish-symbolic");
            } else {
                icon = QIcon(":/res/ukui-rubbish-symbolic.svg");
            }
            QStandardItem *mRubbishClear = new QStandardItem(icon, tr("Garbage Removal"));
            mNaviBar->addItem(mRubbishClear);
        } else if (*iter == PLUGIN_MULTI_TERMINAL) {
            if (QIcon::hasThemeIcon("ukui-miracast-symbolic")) {
                icon = QIcon::fromTheme("ukui-miracast-symbolic");
            } else {
                icon = QIcon(":/res/ukui-miracast-symbolic.svg");
            }
            QStandardItem *mMultiterminal = new QStandardItem(icon, tr("MultiTerminal"));
            mNaviBar->addItem(mMultiterminal);
        } else if (*iter == PLUGIN_TOOL_BOX) {
            if (QIcon::hasThemeIcon("ukui-full-backup-symbolic")) {
                icon = QIcon::fromTheme("ukui-full-backup-symbolic");
            } else {
                icon = QIcon(":/res/ukui-toolkit-symbolic.svg");
            }
            QStandardItem *mToolBox = new QStandardItem(icon, tr("Treasure Chest"));
            mNaviBar->addItem(mToolBox);
        }
    }
    return true;
}
void MainWindow::initMainWorkArea()
{
    QVBoxLayout *mMainVLayout = new QVBoxLayout();
    mMainVLayout->setSpacing(0);
    mMainVLayout->setContentsMargins(0, 0, 0, 0);

    mLabel = new QLabel(this);
    mLabel->setAlignment(Qt::AlignCenter);
    mLabel->setVisible(false);
    mLabel->setText(tr("This function is missing"));

    mStackWidget = new QStackedWidget(this);
    mStackWidget->addWidget(mLabel);

    for (int i = 0; i < m_plugins.size(); i++) {
        KyManagerPluginProvider *plugin = m_plugins.at(i);
        KyManagerPlugin *item = plugin->create();
        QString name = QString::fromStdString(item->name());
        // name.fromStdString(item->name());
        qDebug() << "MainWindow::initMainWorkArea :plugin name :" << name;
        //根据配置文件决定哪些插件是要加载显示
        if (mNeedLoadVector.contains(name)) {
            addKyManagerPluginSort(item);
        }
    }
    //    qDebug() << "MainWindow::initMainWorkArea :迭代器开始之前";
    QMapIterator<QString, KyManagerPlugin *> iterator(mMapPluginIndex);
    int i = 1;
    while (iterator.hasNext()) {
        iterator.next();
        // int index = iterator.key();
        KyManagerPlugin *item = iterator.value();
        std::string str = item->name();
        QString name = QString::fromStdString(str);
        QWidget *widget = item->createWidget();
        mStackWidget->addWidget(widget);
        mMapPlugin.insert(name, i);
        i++;
    }
    mMainVLayout->addWidget(mStackWidget);
    // mMainVLayout->addWidget(mLabel);
    baseBar()->setLayout(mMainVLayout);
}

void MainWindow::addKyManagerPluginSort(KyManagerPlugin *item)
{
    std::string str = item->name();
    QString name = QString::fromStdString(str);
    qDebug() << "MainWindow::addKyManagerPluginSort name:" << name;
    if (name == PLUGIN_BODY_CHECK) {
        mMapPluginIndex.insert(name, item);
    } else if (name == PLUGIN_ISSUS_REPAIR) {
        mMapPluginIndex.insert(name, item);
    } else if (name == PLUGIN_RUBBISH_CLEAR) {
        mMapPluginIndex.insert(name, item);
    } else if (name == PLUGIN_MULTI_TERMINAL) {
        mMapPluginIndex.insert(name, item);
    } else if (name == PLUGIN_TOOL_BOX) {
        mMapPluginIndex.insert(name, item);
    } else {
        qWarning() << "MainWindow::addKyManagerPluginSort 未添加的插件" << name;
    }
}
void MainWindow::initConnectSig()
{
    connect(mNaviBar->listview(), &QListView::clicked, this, &MainWindow::slotNaviClicked);
}
void MainWindow::slotNaviClicked(const QModelIndex &index)
{

    QString str;
    QString data = index.data().toString();
    if (data == tr("PC check")) {
        str = PLUGIN_BODY_CHECK;
    } else if (data == tr("Fault Detection")) {
        str = PLUGIN_ISSUS_REPAIR;
    } else if (data == tr("Garbage Removal")) {
        str = PLUGIN_RUBBISH_CLEAR;
    } else if (data == tr("MultiTerminal")) {
        str = PLUGIN_MULTI_TERMINAL;
    } else if (data == tr("Treasure Chest")) {
        str = PLUGIN_TOOL_BOX;
    } else {
        qWarning() << "MainWindow::slotNaviClicked 错误的index";
    }
    setStackWidget(str);
}
void MainWindow::setStackWidget(QString name)
{
    if (mMapPlugin.contains(name)) {
        int index = mMapPlugin.value(name);
        mStackWidget->setCurrentIndex(index);
    } else {
        mStackWidget->setCurrentIndex(0);
    }
}
void MainWindow::setFirstWidget()
{
    QModelIndex index = mNaviBar->model()->index(0, 0);
    mNaviBar->listview()->setCurrentIndex(index);
    if (!mNeedLoadVector.isEmpty()) {
        QString first = mNeedLoadVector.at(0);
        qDebug() << "MainWindow::setFirstWidget : name " << first;
        setStackWidget(first);
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
	if (event->key() == Qt::Key_F1) {
		kdk::UserManual userManual;
		if (!userManual.callUserManual("kylin-os-manager")) {
			qCritical() << "****** kylin os manager ****** " << "call user manual fail !";
		}
	}
}
